<?php

namespace app\admin\controller;

use app\admin\model\AdminAdmin;
use Gregwar\Captcha\CaptchaBuilder;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\request;

class Login extends Base
{
    public $adminModel;

    public function index(Request $request)
    {

        if ($request->isAjax()) {

            if (!$this->adminModel->captchaCheck($request->post('captcha'))) {
                return json(['code' => 0, 'msg' => '验证码错误']);
            }
            //验证
            try {
                v::input($request->post(), [
                    'username' => v::alnum()->length(5, 64)->setName('用户名'),
                    'password' => v::length(5, 64)->setName('密码'),
                ]);
            } catch (ValidationException $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
            $admin = $this->adminModel->login($request->post());
            if (false == $admin) {
                return json(['code' => 0, 'msg' => '用户名或密码错误']);
            }
            return json(['code' => 200, 'msg' => '登录成功']);
        }
        //是否已经登录
        if ($this->adminModel->isLogin()) {
            return redirect('/admin');
        }
        return view('login/index');
    }

    /**
     * 验证码
     * @param  Request  $request
     */
    public function verify(Request $request)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder(4);
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        (new AdminAdmin)->logout();
        return json(['msg' => '退出成功', 'code' => 200, 'data' => APP_ADMIN.'/login/index']);
    }

    /**
     * 初始化
     */
    protected function initialize()
    {
        $this->adminModel = new AdminAdmin();
    }
}